package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import pojo.vo.BaseRespVO;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

public class BaseController extends HttpServlet {

    /**
     * 读取request对象中的参数，转换成指定类型
     *
     * @param req
     * @param entityClass
     * @param <T>
     * @return
     */
    protected <T> T convertParamsToEntity(HttpServletRequest req, Class<T> entityClass) {
        StringBuilder jsonStr = new StringBuilder();
        try {
            BufferedReader reader = req.getReader();
            String tempStr;
            while ((tempStr=reader.readLine())!= null) {
                jsonStr.append(tempStr);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        T entity = JSON.parseObject(jsonStr.toString(), entityClass);
        return entity;
    }

    //返回结果转换为json,写入输出流
    protected String writerResult(BaseRespVO result, HttpServletResponse resp) {
        return JSON.toJSONString(result);
    }

    protected String writerSuccessResult(Object data, HttpServletResponse resp) {
        BaseRespVO result = new BaseRespVO<>();
        result.setData(data);
        return JSON.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect);
    }

    protected String writerSuccessResult(Object data) {
        BaseRespVO result = new BaseRespVO<>();
        result.setData(data);
        return JSON.toJSONString(result);
    }

    protected String writerErrorResult(String errorMsg, HttpServletResponse resp) {
        BaseRespVO result = new BaseRespVO<>();
        result.setCode(BaseRespVO.CodeType.FAILED.getValue());
        result.setMsg(errorMsg);
        return JSON.toJSONString(result);
    }

    protected String writerErrorResult(String errorMsg) {
        BaseRespVO result = new BaseRespVO<>();
        result.setCode(BaseRespVO.CodeType.FAILED.getValue());
        result.setMsg(errorMsg);
        return JSON.toJSONString(result);
    }
}
